﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Dycox.Linq
{
    public class QueryArgsSurrogate : ICustomTypeDescriptor
    {
        QueryArgs _args;

        QueryProperty[] _properties;

        public QueryArgsSurrogate(QueryArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");

            _args = args;

            Initialize();
        }

        public QueryArgs QueryArgs
        {
            get { return _args; }
        }

        private void Initialize()
        {
            PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(_args);
            List<QueryProperty> list = new List<QueryProperty>();

            foreach (PropertyDescriptor desp in coll)
            {
                var test = desp.Attributes[typeof(QueryArgAttribute)];
                if (test != null)
                    list.Add(CreateProperty(desp));
            }

            _properties = list.ToArray();
        }

        protected virtual QueryProperty CreateProperty(PropertyDescriptor rawProperty)
        {
            return new QueryProperty(rawProperty);
        }

        AttributeCollection ICustomTypeDescriptor.GetAttributes()
        {
            return null;
        }

        string ICustomTypeDescriptor.GetClassName()
        {
            return this.GetType().Name;
        }

        string ICustomTypeDescriptor.GetComponentName()
        {
            return this.GetType().Name;
        }

        TypeConverter ICustomTypeDescriptor.GetConverter()
        {
            return null;
        }

        EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
        {
            return null;
        }

        PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
        {
            return null;
        }

        object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
        {
            return null;
        }

        EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
        {
            return null;
        }

        EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
        {
            return null;
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
        {
            return new PropertyDescriptorCollection(_properties);
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
        {
            return ((ICustomTypeDescriptor)this).GetProperties(null);
        }

        object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
        {
            return _args;
        }

    }
}
